package com.yssoft.controller.app.system;

import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TEnterprise;
import com.yssoft.entity.core.TPersonnel;
import com.yssoft.service.core.AccountsService;
import com.yssoft.service.core.EnterpriseService;
import com.yssoft.service.core.PersonService;
import com.yssoft.service.core.RegisterService;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.verificationCode.CCPRestSDK;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @类名称: RegisterController
 * @类描述: 注册控制器
 * @作者: 洪丰
 * @创建时间:2018年4月29日 上午9:55:48
 */
@CrossOrigin // 解决跨域session问题
@Controller
@RequestMapping("/app/register")
public class AppRegisterController {

	private static Logger logger = Logger.getLogger(AppRegisterController.class);

	@Resource
	private AccountsService accountsService;
	@Resource
	private PersonService personService;
	@Resource
	private EnterpriseService enterpriseService;
	@Resource
	private RegisterService registerService;

	/**
	 * @方法名称: checkPhone
	 * @功能描述: 校验注册手机号
	 * @作者: 洪丰
	 * @创建时间: 2018年4月29日 上午11:36:13
	 * @param phone
	 *            注册手机号
	 * @param request
	 * @return Object
	 */
	@RequestMapping(value = "/checkPhone", method = RequestMethod.POST)
	@ResponseBody
	public Object checkPhone(String phone, HttpServletRequest request) {
		try {
			TAccounts accounts = new TAccounts();
			accounts.setDeleteFlag("0");
			accounts.setLoginName(phone);
			int aList = registerService.queryAccountsByRecord(accounts);

			TPersonnel personnel = new TPersonnel();
			personnel.setDeleteFlag("0");
			personnel.setPhone(phone);
			int pList = registerService.queryPersonneByRecord(personnel);

			if (aList <= 0 && pList <= 0) {
				return AppUtil.returnMapJson("1", "该手机号可注册", null);
			} else {
				return AppUtil.returnMapJson("0", "该手机号已被注册", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AppUtil.returnMapJson("0", "校验失败！请重试", null);
		}
	}

	/**
	 * @方法名称: getVerificationCode
	 * @功能描述: 注册时获取验证码
	 * @作者: 洪丰
	 * @创建时间: 2018年4月29日 上午10:31:57
	 * @param phone
	 *            注册手机号
	 * @return Object
	 */
	@RequestMapping(value = "getVerificationCode", method = RequestMethod.POST)
	@ResponseBody
	public Object getVerificationCode(String phone) {
		Map<String, Object> flag = new HashMap<>();
		flag.put("flag", "9");
		// 传入参数电话号码不可空
		if (phone != null && !"".equals(phone)) {
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount("8a48b55150ac70fd0150acc34f1f01e4", "22ed8d4fa75e45978d35bc245326886d");// 初始化主帐号和主帐号TOKEN
			restAPI.setAppId("8aaf07085995ddef01599b9407660171");// 初始化应用ID

			int num = (int) ((Math.random() * 9 + 1) * 100000);
			// 这里生成验证码与验证码时限时间并存储表

			// sendTemplateSMS
			// 参数1:必选参数 短信接收端手机号码集合，用英文逗号分开，每批发送的手机号数量不得超过100个
			// 参数2:必选参数 模板Id
			// 参数3:可选参数 内容数据，用于替换模板中{序号}
			result = restAPI.sendTemplateSMS(phone, "153391", new String[] { num + "", "1" });
			System.out.println("SDKTestSendTemplateSMS result=" + result);
			if ("000000".equals(result.get("statusCode"))) {
				// 正常返回输出data包体信息（map）
				HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
				Set<String> keySet = data.keySet();
				for (String key : keySet) {
					Object object = data.get(key);
				}
				flag.put("flag", num + "");
				return AppUtil.returnMapJson("1", "获取验证码成功!", flag);
			} else {
				// 异常返回输出错误码和错误信息
				flag.put("flag", "9");
				return AppUtil.returnMapJson("0", "获取验证码失败!错误信息:" + result.get("statusMsg"), flag);
			}
		} else {
			flag.put("flag", "9");
			return AppUtil.returnMapJson("0", "手机号不能为空!", flag);
		}
	}

	/**
	 * @方法名称: saveAccounts
	 * @功能描述: 新建账号
	 * @作者: 洪丰
	 * @创建时间: 2018年4月29日 上午11:30:17
	 * @param phone
	 *            注册手机号
	 * @param password
	 *            注册密码
	 * @return Object
	 */
	@RequestMapping(value = "saveAccounts", method = RequestMethod.POST)
	@ResponseBody
	public Object saveAccounts(String phone, String password) {
		try {
			int accoutsId = registerService.addAcc(phone, password);
			Map<String, Object> user = new HashMap<>();// 用户信息
			user.put("userId", accoutsId);
			return AppUtil.returnMapJson("1", "注册成功!", user);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("注册错误:" + e.getMessage());
			return AppUtil.returnMapJson("0", "注册失败!", null);
		}
	}

	/**
	 * @方法名称: saveEnt
	 * @功能描述: 保存企业信息
	 * @作者: 洪丰
	 * @创建时间: 2018年4月29日 下午1:42:25
	 * @param entity
	 *            企业实体类
	 * @param accoutsId
	 *            账号id
	 * @return Object
	 */
	@RequestMapping(value = "saveEnt", method = RequestMethod.POST)
	@ResponseBody
	public Object saveEnt(TEnterprise entity, Integer accoutsId,HttpServletRequest request) {
		try {
			if (null == accoutsId) {
				return AppUtil.returnMapJson("0", "账号id不能为空!", null);
			}
            Integer entId = registerService.addEntAcc(entity, accoutsId, request);
			Map<String,Object> param=new HashMap<>();
			param.put("entId",entId);
			return AppUtil.returnMapJson("1", "保存成功!", param);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("保存企业信息错误:" + e.getMessage());
			return AppUtil.returnMapJson("0", "保存失败!", null);
		}
	}
	
	/**
	 * 图片上传
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	public Object uploadImage(HttpServletRequest request) throws Exception {
		try{
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
			MultipartFile mFile = mRequest.getFile("img");
			Map<String, Object> fileNames = registerService.compressUploadedFile(mFile);
			return AppUtil.returnMapJson("1", "上传成功!", fileNames);
		} catch (Exception e) {
			e.printStackTrace();
			return AppUtil.returnMapJson("0", "上传失败!", null);
		}
	}
}
